<template>
  <div class="routeList" :class="[setSize == 1 ? 'usual' : 'large']">
    <!-- 侧边栏容器  :style="{ height: maxHeight }"-->
    <el-aside
      class="collection-aside"
      :style="{ height: routeName || isQueryShow ? '70vh' : '23vh' }"
      :class="setTheme == 1 ? 'blue' : 'red'"
    >
      <div class="bg-box" :style="{ height: isCloseBtn ? '100px' : '50px' }">
        <h5 class="my-collection-title">
          <span>{{ routeName }}</span>
          <div style="width: 30px" v-if="!isCloseBtn && isBackBtn">
            <img
              @click="handleClose"
              src="@/assets/images/back.png"
              width="20"
              class="cursor-pointer"
            />
          </div>
        </h5>
        <div>
          <el-select
            v-model="queryType"
            class="mb-10"
            v-if="isCloseBtn"
            @change="handleChangeClear"
          >
            <el-option
              :value="0"
              :label="$t('langName.langName102')"
            ></el-option>
            <el-option
              :value="1"
              :label="$t('langName.langName103')"
            ></el-option>
          </el-select>
          <el-input
            v-model="inputBusroute"
            :placeholder="queryType == 0 ? $t('langName.langName15') : $t('langName.langName23')"
            clearable
            class="input-lineNo"
            @input="handleInputRoute"
            v-if="isCloseBtn"
          ></el-input>
        </div>
      </div>
      <!--线路列表 -->
      <ul
        class="routeLists"
        v-if="routesAll.length != 0 && !isQueryShow"
        :style="{ marginTop: isCloseBtn ? '150px' : '85px' }"
      >
        <li
          class="route-item"
          v-for="(item, index) in routesAll"
          :key="item.id"
          :class="selectList.activeId == item.routeid ? 'activeted' : ''"
          @click="handleChangeRoute(item, 0)"
        >
          <div class="route-title">
            <h6>
              <!-- 1下行，2上行，3环形 -->
              <el-tooltip placement="top" effect="light">
                <div v-if="item.firstBusInfo" slot="content" style="text-align: left;">
                  {{ $t("langName.langName120") }}：{{item.unreachedQuantity}}<br>
                  {{ $t("langName.langName121") }}：{{item.firstBusInfo.busSelfId}}<br>
                  {{ $t("langName.langName122") }}：{{item.firstBusInfo.busnumber}}<br>
                  {{ $t("langName.langName123") }}：{{ $t("langName.langName124") }}{{item.firstBusInfo.busnumbermale}}，{{ $t("langName.langName125") }}{{item.firstBusInfo.busnumberfemale}}<br>
                  {{ $t("langName.langName126") }}：
                    {{item.firstBusInfo.busType == "0" ? $t("langName.langName137") 
                    : item.firstBusInfo.busType == "1" ? $t("langName.langName138") : $t("langName.langName139")}}<br></div>
                <!-- <div v-if="item.generalDesc" slot="content" style="text-align: left;">{{item.generalDesc}}<br></div> -->
                <div v-if="item.secondBusInfo" slot="content" style="text-align: left;">----------------------------------------</div>
                <!-- <div v-if="item.generalDesc.includes('Next')">
                    {{item.secondGeneralDesc}}
                </div><br> -->
                <div v-if="item.secondBusInfo" slot="content" style="text-align: left;">
                  {{ $t("langName.langName127") }}：{{item.nextBusUnreachedQuantity}}<br>
                  {{ $t("langName.langName121") }}：{{item.secondBusInfo.busSelfId}}<br>
                  {{ $t("langName.langName122") }}：{{item.secondBusInfo.busnumber}}<br>
                  {{ $t("langName.langName123") }}：{{ $t("langName.langName124") }}{{item.secondBusInfo.busnumbermale}}，{{ $t("langName.langName125") }}{{item.secondBusInfo.busnumberfemale}}<br>
                  {{ $t("langName.langName126") }}：
                    {{item.secondBusInfo.busType == "0" ? $t("langName.langName137") 
                    : item.secondBusInfo.busType == "1" ? $t("langName.langName138") : $t("langName.langName139")}}<br></div>
                <div v-if="predictionData1.generalDesc" slot="content" style="text-align: left;">{{predictionData1.generalDesc}}<br></div>
                <div 
                      v-if="predictionData1.firstBusInfo"
                      slot="content" style="text-align: left;"
                    >
                      {{ $t("langName.langName120") }}：{{predictionData1.unreachedQuantity}}<br>
                      {{ $t("langName.langName121") }}：{{predictionData1.firstBusInfo.busSelfId}}<br>
                      {{ $t("langName.langName122") }}：{{predictionData1.firstBusInfo.busnumber}}<br>
                      {{ $t("langName.langName123") }}：{{ $t("langName.langName124") }}{{predictionData1.firstBusInfo.busnumbermale}}，
                                                        {{ $t("langName.langName125") }}{{predictionData1.firstBusInfo.busnumberfemale}}<br>
                      {{ $t("langName.langName126") }}：
                        {{predictionData1.firstBusInfo.busType == "0" ? $t("langName.langName137") 
                        : predictionData1.firstBusInfo.busType == "1" ? $t("langName.langName138") : $t("langName.langName139")}}<br></div>
                    <div v-if="predictionData1.secondBusInfo">----------------------------------------</div>
                    <div 
                      v-if="predictionData1.secondBusInfo" 
                      slot="content" style="text-align: left;"
                    >
                      <!-- <div v-if="predictionData1.generalDesc.includes('Next')">
                        {{predictionData1.secondGeneralDesc}}<br>
                      </div> -->
                      {{ $t("langName.langName127") }}：{{predictionData1.nextBusUnreachedQuantity}}<br>
                      {{ $t("langName.langName121") }}：{{predictionData1.secondBusInfo.busSelfId}}<br>
                      {{ $t("langName.langName122") }}：{{predictionData1.secondBusInfo.busnumber}}<br>
                      {{ $t("langName.langName123") }}：{{ $t("langName.langName124") }}{{predictionData1.secondBusInfo.busnumbermale}}，
                                                        {{ $t("langName.langName125") }}{{predictionData1.secondBusInfo.busnumberfemale}}<br>
                      {{ $t("langName.langName126") }}：
                        {{predictionData1.secondBusInfo.busType == "0" ? $t("langName.langName137") 
                        : predictionData1.secondBusInfo.busType == "1" ? $t("langName.langName138") : $t("langName.langName139")}}<br></div>
                <!-- <div v-else slot="content" style="text-align: left;">{{ $t("langName.langName128") }}</div> -->
                <el-button>{{ item.routename }}</el-button>
              </el-tooltip>
              <!-- {{ item.routename }} -->
              <span class="up-down" v-if="item.rundirection == 1">Down</span>
              <span class="up-down" v-if="item.rundirection == 2">Up</span>
              <span class="up-down" v-if="item.rundirection == 3">Circle</span>
            </h6>
            <div>
              <span
                v-if="item.runDirection != 3 && item.rundirection != 3"
                class="icon iconfont icon-jiantou_zuoyouqiehuan changeInfo"
                @click.stop="handleChangeUpAndDown(item)"
              ></span>
              <img
                @click.stop="handleCollect(item, index)"
                :src="
                  item.isCollect
                    ? require('@/assets/images/star.png')
                    : require('@/assets/images/unstar.png')
                "
                alt=""
              />
              <i
                class="el-icon-delete"
                style="margin-left: 10px"
                v-if="isHistory"
                @click.stop="handleDelHistory(item)"
              ></i>
            </div>
          </div>
          <div style="font-size: 14px; color: gray; margin-top: -10px">
            <div style="margin-bottom: 3px">
              {{ $t("langName.langName108") }}{{ item.startStation }}
            </div>
            <div>{{ $t("langName.langName109") }}{{ item.endStation }}</div>
          </div>
        </li>
        <div
          @click="isMore = !isMore"
          class="more cursor-pointer"
          v-if="routesAllTemp.length > 2"
        >
          <i class="el-icon-arrow-down" v-if="isMore">{{
            $t("langName.langName64")
          }}</i>
          <i class="el-icon-arrow-up" v-else>{{ $t("langName.langName63") }}</i>
        </div>
        <div
          @click="handleDelAllHistory"
          class="more cursor-pointer"
          v-if="isHistory"
        >
          {{ $t("langName.langName62") }}
        </div>
      </ul>

      <div v-if="routesAll.length == 0 && !isQueryShow">
        <el-empty :description="$t('langName.langName43')"></el-empty>
      </div>
      <div v-if="isQueryShow" style="margin-top: 140px;">
        <el-card class="box-card">
          <div class="box" v-if="queryType == 0">
            <div
              class="feed-list cursor-pointer"
              v-for="item in routeNameList"
              :key="item.routeid"
              @click="handleChangeRoute12(item)"
            >
              <div class="title">
                <div>{{ item.routename }}</div>
              </div>
            </div>
          </div>
          <div class="box" v-if="queryType == 1">
            <div
              class="feed-list cursor-pointer"
              v-for="(item, index) in stationNameList"
              :key="index"
              @click="handleChangeRoute11(item)"
            >
              <div class="title">
                <div>{{ item.stationname }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </el-aside>
  </div>
</template>

<script>
import {
  addCollect,
  delCollect,
  addHistory,
  getRouteInfo,
  getStationRoute,
  getPredict,
} from "@/api/collect";
import { mapState } from "vuex";
export default {
  name: "routeList",
  props: ["collectDatas", "predictionData" ,"routeName", "isCloseBtn", "isBackBtn", "isHistory"],
  data() {
    return {
      routesAll: [], //线路列表
      inputBusroute: "", //搜索内容
      maxHeight: "", //最大高度
      routeIdData: "",
      isMore: this.$store.state.isMore,
      routesAllTemp: [],
      setSize: 1,
      refreshTime: 1,
      setTheme: 1,
      isQueryShow: false,
      routeNameList: [],
      stationNameList: [],
      queryType: 0,
      selectList: {
        activeId: null,
        list: []
      },
      predictionData1:[],
      lastClickTime: "",//记录当前时间
    };
  },
  computed: {
    ...mapState(["changeSize", "changeRefresh", "changeTheme"]),
  },
  watch: {
    // 监听线路列表变化，如果数据的长度大于2并且isMore为true也就是初始化时截取前两个数据，否则如果长度小于等于2显示全部
    collectDatas: {
      deep: true,
      handler(newVal) {
        // if(this.routesAll.length < 1){
          let newList = JSON.parse(JSON.stringify(newVal));
          newList.forEach(item => {
            this.selectList.list.forEach(e => {
              if (item.routeid == e.routeid) {
                item.rundirection = e.rundirection;
                item.startStation = e.startStation;
                item.endStation = e.endStation;
              }
            })
          })
          this.routesAll = this.routesAllTemp = newList;
          if (this.routesAllTemp.length > 2 && this.isMore) {
            this.routesAll = this.routesAllTemp.slice(0, 2);
          } else {
            this.routesAll = this.routesAllTemp;
          }
        // }
      },
    },
    // 是否显示全部线路列表
    isMore: {
      handler(newVal) {
        if (newVal) {
          if (this.routesAllTemp.length > 2) {
            this.routesAll = this.routesAllTemp.slice(0, 2);
          } else {
            this.routesAll = this.routesAllTemp;
          }
        } else {
          this.routesAll = this.routesAllTemp;
        }
      },
    },
    changeSize: {
      handler(newVal) {
        this.setSize = newVal;
      },
    },
    changeTheme(newVal) {
      this.setTheme = newVal;
    },
    predictionData: {
      deep: true,
      handler(newVal) {
        this.predictionData1 = newVal
      },
    },
  },
  mounted() {
    let maxHeight =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;
    this.maxHeight = maxHeight + "px";
    this.setSize = this.$store.state.changeSize;
    this.setTheme = this.$store.state.changeTheme;
    // 将父组件传递过来的线路列表数据进行赋值（不能直接进行遍历，因为进行搜索时需要改变列表显示数据）
    if (this.$store.state.routeListStore && !this.isCloseBtn) {
      this.selectList.activeId = this.$store.state.routeListStore.routeid;
    } else {
      this.selectList.activeId = "";
      this.selectList.list = [];
    }
    this.routesAllTemp = this.collectDatas;
    if (this.routesAllTemp.length > 2) {
      this.routesAll = this.routesAllTemp.slice(0, 2);
    } else {
      this.routesAll = this.routesAllTemp;
    }
    this.predictionData1 = this.routesAll
  },

  methods: {
    // 点击弹窗线路信息-进入线路详情
    handleChangeRoute11(item) {
      this.$store.commit("setRouteListStore", item);
      this.$router.push({
        name: "routeDetail",
        params: {
          routeName: item.stationname,
          stationid: item.stationid,
          segmentid: item.segmentid,
          index: 0,                                   
        },
      });
    },
    // 点击弹窗线路信息-进入线路详情
    handleChangeRoute12(item) {
      this.$store.commit("setRouteListStore", item);
      this.$router.push({
        name: "routeDetail",
        params: {
          routeName: item.routename,
          stationid: item.routeid,
          // segmentid: item.segmentid,
          index: 1,
        },
      });
    },
    // 获取站点所有线路
    // 获取选中站点的所有线路
    async getStationRoute(item) {
      clearInterval(this.setTime);
      let params = {
        stationId: item.stationid,
        userId: localStorage.getItem("userId")
          ? localStorage.getItem("userId")
          : "", //用户id
      };
      let { status, data } = await getStationRoute(params);
      if (status == 200) {
        this.collectDatas = data;
        this.isCollecData = true;
      }
      this.setTime = setInterval(async () => {
        let { status, data } = await getStationRoute(params);
        if (status == 200) {
          this.collectDatas = data;
          this.isCollecData = true;
        }
      }, this.refreshTime);
    },
    // 搜索功能 输入线路号查询
    async handleInputRoute() {
      this.stationNameList = [];
      this.routeNameList = [];
      this.lastClickTime = +new Date() //添加调用方法的时间标识
      // console.log('this.lastClickTime',this.lastClickTime)
      if (this.inputBusroute) {
        this.isQueryShow = true;
        let params = {
          routeName: this.inputBusroute,
          userId: localStorage.getItem("userId"),
          type: Number(this.queryType),
        };
        let lastClickTime = this.lastClickTime //最后一次点击时间，防止频繁操作
        // console.log('this.lastClickTime',lastClickTime)
        let { status, data } = await getRouteInfo(params);
        if (status == 200) {
          if (lastClickTime == this.lastClickTime) { //判断时间是否一致，如果一致，则进行操作（不一致则代表是先请求的接口后返回，不进行操作即可
            if (this.queryType == 1) {
                this.stationNameList = data;
              } else {
                this.routeNameList = data;
            }
          }
        }
      } else {
        this.isQueryShow = false;
      }
      this.addHistory();
    },
    handleChangeClear() {
      this.isQueryShow = false;
      this.inputBusroute = "";
      this.routesAll = [];
      this.routeName = "";
    },
    // 切换是否收藏
    handleCollect(item, index) {
      if (!localStorage.getItem("userId")) {
        this.$message({
          message: this.$t("langName.langName33"),
          type: "warning",
        });
      } else {
        let params = {
          userid: localStorage.getItem("userId"),
          routeid: item.routeid,
          rundirection: item.runDirection || item.rundirection,
          routename: item.routename,
        };
        if (item.isCollect) {
          this.delCollect(params, item, index);
        } else {
          this.addCollect(params, item);
        }
      }
    },
    // 添加收藏
    async addCollect(params, item) {
      let { status, message } = await addCollect(params);
      if (status == 200) {
        this.$message({
          message: this.$t("langName.langName44"),
          type: "success",
        });
        item.isCollect = !item.isCollect;
      } else {
        this.$message({
          message: message,
          type: "error",
        });
      }
    },
    // 取消收藏
    async delCollect(params, item, index) {
      let { status, message } = await delCollect(params);
      if (status == 200) {
        this.$message({
          message: this.$t("langName.langName45"),
          type: "success",
        });
        item.isCollect = !item.isCollect;
        // 如果是收藏---传递给父元素，刷新收藏列表
        if (!this.isBackBtn) {
          this.routesAllTemp.splice(index, 1);
          this.routesAll = this.routesAllTemp;
          // this.$emit("handleCollect", item);
        }
      } else {
        this.$message({
          message: message,
          type: "error",
        });
      }
    },
    // 切换线路
    handleChangeUpAndDown(item) {
      item.rundirection =
        item.rundirection == 1 ? "2" : item.rundirection == 2 ? "1" : "";
      [item.startStation, item.endStation] = [
        item.endStation,
        item.startStation,
      ];
      let params = JSON.parse(JSON.stringify(item))
      this.saveList(params);
      this.selectList.activeId = item.routeid;
      this.$store.commit("setIsMore", this.isMore);
      this.$emit("handleChangeRoute", item);
    },

    // 关闭弹窗
    handleClose() {
      this.$emit("handleClose");
    },
    // 点击线路，查看线路详情
    handleChangeRoute(item, index) {
      this.selectList.activeId = item.routeid;
      this.$emit("handleChangeRoute", item, index);
    },

    // 添加用户搜索历史
    async addHistory() {
      if (!this.isCloseBtn || this.isBackBtn) return;
      if (!localStorage.getItem("userId")) return;
      let params = {
        userid: localStorage.getItem("userId"),
        routeid: this.routesAll[0].routeid,
        rundirection: this.routesAll[0].rundirection, //运行方向
      };
      await addHistory(params);
    },
    // 删除单条历史记录
    handleDelHistory(item) {
      this.$emit("handleDelHistory", item);
    },
    // 删除全部历史记录
    handleDelAllHistory() {
      this.$emit("handleDelAllHistory");
    },
    // 储存点击过的数据
    saveList(item) {
      if (this.selectList.list.length) {
        let idList = this.selectList.list.map(e => { return e.routeid });
        if (idList.includes(item.routeid)) {
          this.selectList.list.forEach(e => {
            if (e.routeid == item.routeid) e.rundirection = item.rundirection;
          });
          return;
        };
        this.selectList.list.push(item);
      } else {
        this.selectList.list.push(item);
      }
    }
  },
};
</script>
<style>
@import "../assets/css/common.css";
</style>
<style lang="scss" scoped>
.usual .my-collection-title {
  font-size: 16px;
}
.usual h6 {
  font-size: 18px !important;
}
.usual .up-down {
  font-size: 12px;
}
.usual .current-busroute,
.usual .current-bus-time {
  font-size: 14px;
}
.usual .distanceStyle {
  font-size: 14px;
}
.usual .more {
  font-size: 14px;
}

.large .my-collection-title {
  font-size: 18px;
}
.large h6 {
  font-size: 20px !important;
}
.large .up-down {
  font-size: 14px;
}
.large .current-busroute,
.large .current-bus-time {
  font-size: 14px;
}
.large .distanceStyle {
  font-size: 16px;
}
.large .more {
  font-size: 16px;
}
.blue .up-down {
  border: 1px solid #0156ff;
  color: #0156ff;
}
.blue .current-busroute .current-bus-time {
  color: #0156ff;
}
.red .up-down {
  // border: 1px solid rgb(253, 23, 23);
  // color: rgb(253, 23, 23);
  border: 1px solid #0156ff;
  color: #0156ff;
}
.red .current-busroute .current-bus-time {
  // color: rgb(253, 23, 23);
  color: #0156ff;
}

.bg-box {
  position: fixed;
  top: 90px;
  z-index: 2;
  width: 330px;
  padding: 20px 20px 0 20px;
  left: 10px;
  right: 0;
  background: #fff;
}
// 左侧边
.collection-aside {
  position: fixed;
  box-sizing: border-box;
  top: 80px;
  left: 0;
  box-sizing: border-box;
  // width: calc(100% - 1460px) !important;
  width: 380px !important;
  text-align: left;
  padding: 20px 30px 120px 20px;
  z-index: 999;
  background: #fff;
  margin: 10px;

  // 标题
  .my-collection-title {
    display: flex;
    justify-content: space-between;
    padding-bottom: 20px;
    height: 30px;
  }
  .el-icon-close {
    cursor: pointer;
  }
  // 输入框
  .input-lineNo {
    height: 40px;
    line-height: 40px;
  }
  // 选择框
  .select-favoritesTab {
    width: 50%;
    height: 40px;
  }
  // 线路列表
  .routeLists {
    background: #f4f6fa;
    margin-top: 110px;
    .activeted {
      box-shadow: 0 0 8px rgba(180, 180, 180, 0.6);
    }
    .route-item {
      padding: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ddd;

      cursor: pointer;
      .route-title {
        display: flex;
        justify-content: space-between;
        img {
          margin-left: 10px;
          width: 15px;
        }
      }
      h6 {
        position: relative;
        display: flex;
        align-items: center;
        font-family: 700;
        margin-bottom: 20px;
      }
      .up-down {
        display: inline-block;
        margin-left: 5px;
        padding: 1px 5px;
      }
      .current-busroute {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .current-bus-time {
          position: relative;
          display: flex;
          align-items: center;
          font-weight: 700;
        }
        .current-bus-time::after {
          content: "";
          display: inline-block;
          position: absolute;
          top: -8px;
          right: -2px;
          height: 16px;
          width: 16px;
          transform: rotate(45deg);
          background: url("@/assets/images/wifi.png") no-repeat;
        }
      }
      .distanceStyle {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #b4b4b5;
        margin-top: 10px;
      }
    }
    .route-item:last-child {
      border-bottom: 1px solid transparent;
    }
  }
}
.box-card {
  height: 450px;
  width: 330px;
  overflow: hidden;
  position: fixed;
}
::v-deep .el-card__body {
  height: 100%;
  overflow: auto;
}
.box {
  height: 100%;
  overflow: auto;
  color: #000;
}
.box::-webkit-scrollbar {
  width: 0px;
}

.feed-list {
  padding: 20px 0;
  border-bottom: 1px solid #ecf5ff;
  .title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    font-weight: 600;
  }
}

.changeInfo {
  width: 50px;
}
::-webkit-scrollbar {
  width: 0;
  display: none;
}
.more {
  text-align: center;
  padding: 10px;
  color: #c2bfbf;
}
::v-deep .el-empty {
  padding: 200px 0;
}
</style>
